<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Rules extends MY_Controller {

	public function __construct() {
		parent::__construct();
		$this->load->model('rules_model', 'rules');
	}

	public function posts() {
		$ruleid = $this->uri->segment(4);
		if (FALSE == $ruleid) {
			$this->_write();
		} else {
			$this->_edit($ruleid);
		}
	}

	public function doswitch() {
		$retCode = 0;
		$ruleid = $this->input->post('ruleid');
		$disabled = $this->input->post('disabled');
		$data = array('disabled' => $disabled);
		$ret = $this->rules->edit($ruleid, $data);
		if (!$ret) {
			$retCode = -1;
		}
		exit(json_encode(array('code' => $retCode)));	
	}

	private function _write() {
		if ( empty($_POST) ) {
			$this->load->view('admin/rules/form.html');
		} else {
			$data = $this->input->post();
			$result = $this->rules->add($data);
			redirect('admin/rules/index');
		}
	}

	private function _edit($ruleid) {
		if (empty($_POST)) {
			$data = $this->rules->show($ruleid);
			$this->_data['rule'] = $data;
			$this->load->view('admin/rules/form.html', $this->_data);

		} else {
			$data = $this->input->post();
			$this->rules->edit($ruleid, $data);
			redirect('admin/rules/index');
		}
	}


	public function index() {
		$this->load->library('pagination');
		$perPage = 3;

		$config['base_url'] = site_url('admin/rules/index');
		$config['total_rows'] = $this->db->count_all_results('crawl_rules');
		$config['per_page'] = $perPage;
		$config['uri_segment'] = 4;
		$config['first_link'] = '第一页';
		$config['prev_link'] = '上一页';
		$config['next_link'] = '下一页';
		$config['last_link'] = '最后一页';

		$this->pagination->initialize($config);
		$this->_data['links'] = $this->pagination->create_links();

		$offset = $this->uri->segment(4);
		$this->db->limit($perPage, $offset);

		$this->_data['rules'] = $this->rules->get_reles();
		$this->load->view('admin/rules/index.html', $this->_data);
	}

}